package com.dlc.felear.xiaoensale.helper;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.TypeReference;
import com.dlc.felear.xiaoensale.activity.SuttleWeightActivity;
import com.dlc.felear.xiaoensale.constant.Constant;
import com.dlc.felear.xiaoensale.customView.ShowTispMsgDialog;
import com.dlc.felear.xiaoensale.dao.CookingMenuDao;
import com.dlc.felear.xiaoensale.entity.CookingMenu;
import com.dlc.felear.xiaoensale.entity.DeviceInfo;
import com.dlc.felear.xiaoensale.entity.MenuFoodMaterial;
import com.dlc.felear.xiaoensale.entity.Msg;
import com.dlc.felear.xiaoensale.entity.Operator;
import com.dlc.felear.xiaoensale.entity.QueryMsgInfo;
import com.dlc.felear.xiaoensale.entity.SideDish;
import com.dlc.felear.xiaoensale.utils.DateTimeUtil;
import com.dlc.felear.xiaoensale.utils.HandleSocketDataUtil;
import com.dlc.felear.xiaoensale.utils.HttpApi;
import com.dlc.felear.xiaoensale.utils.JasyptUtil;
import com.dlc.felear.xiaoensale.utils.TimeUtils;
import com.dlc.felear.xiaoensale.utils.UuidUtil;
import com.itdlc.android.library.utils.APPDidUtil;
import com.zhy.http.okhttp.callback.StringCallback;

import org.apache.commons.lang3.StringEscapeUtils;
import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class SendData {
    private static String TAG = "SendData";

    public static void sendRecordMenuInfo(final CookingMenu cookingMenu){
        try {
            Log.e(TAG,"上传炒菜记录:"+JsonHelper.toJson(cookingMenu));
            HashMap<String,Object> bp=new HashMap<>();
            List<HashMap<String,Object>> fl=new ArrayList<>();
            float totalWeight=(Float.parseFloat(cookingMenu.getSpecification())*1000);
            for(MenuFoodMaterial foodMaterial:cookingMenu.getFoodMaterials()){
                if(!TextUtils.isEmpty(foodMaterial.getFoodName())&&foodMaterial.getFoodid()!=0&&foodMaterial.getWeight()>0){
                    HashMap<String,Object> tempM=new HashMap<>();
                    //食材菜谱id
                    tempM.put("foodmenuId",cookingMenu.getId());
                    //食材格子号
                    tempM.put("scaleNo",foodMaterial.getNumber());
                    //食材id
                    tempM.put("id",UuidUtil.getUuid());
                    tempM.put("foodid",foodMaterial.getFoodid());
                    //食材重量
                    tempM.put("weight",foodMaterial.getWeight());
                    //食材比例
                    float tempweightProportion=(float) foodMaterial.getWeight()/(float)totalWeight;
                    tempM.put("weightProportion",(int)(tempweightProportion*100));
                    fl.add(tempM);
                }
            }
            //菜谱id
            bp.put("foodmenuId",cookingMenu.getId());
            //设备编号
            bp.put("deviceId",APPDidUtil.getAppDid());
            bp.put("cookStime", DateTimeUtil.getCurrentTImeYMDHMS());
            bp.put("timeCost",cookingMenu.getDuration());
            //菜谱名称
            bp.put("foodmenuName",cookingMenu.getName());
            //菜谱规格
            bp.put("weight",totalWeight);
            //操作步骤
            bp.put("stepJson",JsonHelper.toJson(cookingMenu.getOperators()));
            //食材
            bp.put("proportionList",fl);
            String sign=JasyptUtil.getInstance().getSign(bp);
            bp.put("sign",sign);
            Log.e(TAG,"上传炒菜记录:"+JsonHelper.toJson(bp));
            OkHttpManager.HttpPostJson(HttpApi.URL_ADDORGFOODMENURECORD, bp, new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    Log.e(TAG,"上传上传炒菜:"+e.getMessage());
                }

                @Override
                public void onResponse(String response, int id) {
                    Log.e(TAG,"炒菜记录上传成功:"+response);
                    try {
                        Msg msg=JsonHelper.parserJson(response,Msg.class);

                    }catch (Exception e){

                    }
                }
            });
        }catch (Exception e){
            Log.e(TAG,"炒菜记录上传成功:"+e.getMessage());
        }
    }


    public static void sendMenuInfo(final Context context, final CookingMenu cookingMenu, final int isdelete) {
        try {
            if(TextUtils.isEmpty(cookingMenu.getParam1())){
                showMsg(context,"菜谱公式为空，请添加公式值再上传");
                return;
            }
            if(cookingMenu.getOperators()==null||cookingMenu.getOperators().isEmpty()){
                showMsg(context,"菜谱炒菜步骤为空，请添加炒菜步骤再上传");
                return;
            }
            if(cookingMenu.getFoodMaterials()==null||cookingMenu.getFoodMaterials().isEmpty()){
                showMsg(context,"菜谱食材为空，请添加食材再上传");
                return;
            }
            HashMap<String, Object> bp = new HashMap<>();
            List<HashMap<String, Object>> fl = new ArrayList<>();
            int totalWeight = Integer.parseInt(cookingMenu.getSpecification()) * 1000;
            for (MenuFoodMaterial foodMaterial : cookingMenu.getFoodMaterials()) {
                if (!TextUtils.isEmpty(foodMaterial.getFoodName()) && foodMaterial.getFoodid() != 0 && foodMaterial.getWeight() > 0) {
                    HashMap<String, Object> tempM = new HashMap<>();
                    //食材菜谱id
                    tempM.put("foodmenuId", cookingMenu.getId());
                    //食材格子号
                    tempM.put("scaleNo", foodMaterial.getNumber());
                    //食材id
                    tempM.put("id", UuidUtil.getUuid());
                    tempM.put("foodid", foodMaterial.getFoodid());
                    //食材重量
                    tempM.put("weight", foodMaterial.getWeight());
                    //食材比例
                    float tempweightProportion = (float) foodMaterial.getWeight() / (float) totalWeight;
                    tempM.put("weightProportion", (int) (tempweightProportion * 100));
                    fl.add(tempM);
                }
            }
            //设备编号
            bp.put("deviceId", APPDidUtil.getAppDid());
            //菜谱名称
            bp.put("state", isdelete);
            bp.put("vdesc", cookingMenu.getDesc());
            bp.put("param1", cookingMenu.getParam1());
            bp.put("param2", cookingMenu.getParam2());
            bp.put("param3", cookingMenu.getParam3());
            bp.put("param4", cookingMenu.getParam4());
            //菜谱名称
            bp.put("foodmenuName", cookingMenu.getName());
            //炒菜类型
            bp.put("cookingType", cookingMenu.getCookingType());
            //食材分类名称
            bp.put("menuMainFood", cookingMenu.getMenuMainFood());
            //食材分类Id
            bp.put("menuMainFoodId", cookingMenu.getMenuMainFoodId());
            //菜谱规格
            bp.put("weight", Integer.parseInt(cookingMenu.getSpecification()) * 1000);
            //操作步骤
            bp.put("stepJson", JsonHelper.toJson(cookingMenu.getOperators()));
            //食材
            bp.put("proportionList", fl);
            if (fl.isEmpty()) {
                Toast.makeText(context, "食材列表为空，请添加食材", Toast.LENGTH_SHORT).show();
                return;
            }
            if (cookingMenu.getOperators().isEmpty()) {
                Toast.makeText(context, "炒菜步骤为空，请添加炒菜步骤", Toast.LENGTH_SHORT).show();
                return;
            }
            Log.e(TAG, "proportionList:" + JsonHelper.toJson(fl));
            String sign = JasyptUtil.getInstance().getSign(bp);
            bp.put("sign", sign);
            Log.e(TAG, "上传菜谱:" + JsonHelper.toJson(bp));
//            Log.e(TAG, "上传菜谱:" + JsonHelper.toJson(bp) + " proportionList size=" + fl.size());
            OkHttpManager.HttpPostJson(HttpApi.URL_ADDORGFOODMENU, bp, new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    Log.e(TAG, "上传菜谱:" + e.getMessage());
                    Toast.makeText(context, "网络异常", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onResponse(String response, int id) {
                    Log.e(TAG, "菜谱上传成功:" + response);
                    try {
                        Msg msg = JsonHelper.parserJson(response, Msg.class);
                        if (msg != null && msg.getCode() == 1) {
                            CookingMenuDao cookingMenuDao = new CookingMenuDao(context);
                            cookingMenuDao.deleteAllInfo(cookingMenu);
                            HandleSocketDataUtil.getInstance(context).pushMenuDataToOtherDevice(msg.getData()
                                    ,cookingMenu.getMachineModoel());
                            sendUpdateMenuInfo(msg.getData(),cookingMenu.getMachineModoel(),context,cookingMenuDao);
                        } else {
                            Toast.makeText(context, msg.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        Toast.makeText(context, "数据异常:"+e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "sendMenuInfo:" + e.getMessage());
            showMsg(context, "数据解析异常:" + e.getMessage());
        }
    }


    /**
     * @param context
     */
    public static void sendUpdateMenuInfo(String menuId,String machineModoel, final Context context, final CookingMenuDao cookingMenuDao) {

        Log.e(TAG, "更新参数 sendUpdateMenuInfo menuId=" +menuId+" machineModoel="+machineModoel );
        if(TextUtils.isEmpty(menuId)){
            return;
        }
        Map<String, Object> paramer = new HashMap<>();
        String id = stringQuchong(menuId);
        paramer.put("foodmenuId", id);
        paramer.put("machineModoel", machineModoel);
        Log.e(TAG, "更新参数 sendUpdateMenuInfo=" + JsonHelper.toJson(paramer));
//        getOrgFoodMenu
        OkHttpManager.HttpPostJson(HttpApi.URL_GETORGFOODMENU, paramer, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
//                Log.e(TAG, "sendCarInfo=" + e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "sendUpdateMenuInfo=" + response);
                try {
                    UpdateMenuInfoList list = JsonHelper.parserJson(response, UpdateMenuInfoList.class);
                    if (list != null && list.getCode() == 1) {
                        Log.e(TAG,"更新成功:"+JsonHelper.toJson(list));
                        saveMenuInfo(list.getData(), cookingMenuDao, context);
                    } else {
                        showMsg(context, "菜谱更新失败:" + list.getMsg());
                    }
                } catch (Exception e) {
                    showMsg(context, "菜谱更新失败:" + e.getMessage());
                }
            }
        });
    }

    public static void showMsg(Context context, String msg) {
        try {
            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
        }catch (Exception e){

        }
    }

    private static void saveMenuInfo(List<UpdateMenuInfoList.MenuInfo> list, CookingMenuDao cookingMenuDao, Context context) {
        try {
            if (!list.isEmpty()) {
                showMsg(context, "菜谱更新成功");
                Log.e(TAG, "saveMenuInfo list:" + JsonHelper.toJson(list));
                for (UpdateMenuInfoList.MenuInfo menuInfo : list) {
                    String newId=menuInfo.getId() + "_" + menuInfo.getMachineModoel()+Integer.toString(menuInfo.getWeight()/1000);
                    CookingMenu cookingMenu1 = cookingMenuDao.queryById(newId);
                    if (cookingMenu1 == null) {
                        cookingMenu1=new CookingMenu();
                        cookingMenu1.setId(newId);
                        cookingMenu1.setName(menuInfo.getFoodmenuName());
                    }
                    int type=menuInfo.getIsdelete();
                    cookingMenu1.setType(type);
                    cookingMenu1.setCookingType(menuInfo.getCookingType());
                    cookingMenu1.setMachineModoel(menuInfo.getMachineModoel());
                    cookingMenu1.setSpecification(Integer.toString(menuInfo.getWeight()/1000));
                    cookingMenu1.setUpdateTime(TimeUtils.getCurrrentTimeYMDHMS());
                    cookingMenu1.setDesc(menuInfo.getVdesc());
                    cookingMenu1.setUpdateTime(TimeUtils.getCurrrentTimeYMDHMS());
                    cookingMenu1.setLevel(menuInfo.getMachineModoel());
                    cookingMenu1.setParam1(menuInfo.getParam1());
                    cookingMenu1.setParam2(menuInfo.getParam2());
                    cookingMenu1.setParam3(menuInfo.getParam3());
                    cookingMenu1.setParam4(menuInfo.getParam4());
                    cookingMenu1.setPic(menuInfo.getPic());
                    cookingMenu1.setUploaded(1);
                    cookingMenu1.setOperators(saveActionStepInfo(cookingMenu1.getId(), menuInfo.getStepJson()));
                    cookingMenu1.setFoodMaterials(saveMenuMenuFoodMaterialInfo(cookingMenu1.getId(), menuInfo.getProportionList()));
                    cookingMenuDao.createOrUpdateAll(cookingMenu1);
                    CookingMenuMangerHelper.getInstance(context, new CookingMenuDao(context)).updateCookingMenu(cookingMenu1);
                }
            }
        } catch (Exception e) {
            showMsg(context, "菜谱更新失败:" + e.getMessage());
        }
    }

    private static List<MenuFoodMaterial> saveMenuMenuFoodMaterialInfo(String cid, List<UpdateMenuInfoList.MenuInfo.ProportionList> proportionList) {
        List<MenuFoodMaterial> list = new ArrayList<>();
        try {
            if (null != proportionList) {
                for (UpdateMenuInfoList.MenuInfo.ProportionList proportion : proportionList) {
                    MenuFoodMaterial foodMaterial = new MenuFoodMaterial();
                    foodMaterial.setCid(cid);
                    foodMaterial.setId(proportion.getId());
                    foodMaterial.setFoodName(proportion.getFoodName());
                    foodMaterial.setFoodid(proportion.getFoodid());
                    foodMaterial.setNumber(proportion.getScaleNo());
                    foodMaterial.setWeight(proportion.getWeight());
                    foodMaterial.setType(Constant.FOODS_TYPE_2);
                    list.add(foodMaterial);
                }
            }
        } catch (Exception e) {
        }

        return list;
    }

    private static List<Operator> saveActionStepInfo(String id, String stepJson) {
        List<Operator> list = null;
        try {
            Log.e(TAG, "saveActionStepInfo id:" + id + " stepJson:" + stepJson);
            list = JsonHelper.parserJson(StringEscapeUtils.unescapeJava(stepJson),
                    new TypeReference<List<Operator>>() {
                    });
        } catch (Exception e) {
            Log.e(TAG, "saveActionStepInfo=" + e.getMessage());
        }
        return list;
    }

    private static String stringQuchong(String id) {
        if (id.contains("_")) {
            return id.substring(0, id.indexOf("_"));
        }
        return id;
    }

    /**
     * 毛菜上报
     *
     * @param data
     * @param type
     */
    public static void uplaodFoodMaterial(List<MenuFoodMaterial> data, int type) {
        if (data == null || data.isEmpty()) {
            Msg msg = new Msg();
            msg.setMsg("数据为空，请查正后再上传");
            msg.setMessage("数据为空，请查正后再上传");
            resultCallback(msg, Constant.EVENTBUS_TAG_HTTP_RESULT);
            return;
        }
        ArrayList<Map<String, Object>> list = new ArrayList();
        for (MenuFoodMaterial foodMaterial : data) {
            Map<String, Object> temp = new HashMap<>();
            temp.put("deviceId", APPDidUtil.getAppDid());
            temp.put("scaleNo", foodMaterial.getNumber());
            temp.put("weight", foodMaterial.getWeight());
            temp.put("productId", foodMaterial.getFoodid());
            list.add(temp);
        }
        HashMap<String, Object> bp = new HashMap<>();
        bp.put("type", type);
        bp.put("poundList", list);
        Log.e(TAG, "paramer=" + JsonHelper.toJson(bp));
        OkHttpManager.HttpPostJson(HttpApi.URL_RECORDPOUND, bp, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                Log.e(TAG, HttpApi.URL_RECORDPOUND);
                Log.e(TAG, e.getMessage());
                Msg msg = new Msg();
                msg.setMsg("设备网络异常，请连接网络");
                msg.setMessage("设备网络异常，请连接网络");
                resultCallback(msg, Constant.EVENTBUS_TAG_HTTP_RESULT);
            }

            @Override
            public void onResponse(String s, int i) {
                try {
                    Msg msg = JsonHelper.parserJson(s, Msg.class);
                    if (msg != null) {
                        resultCallback(msg, Constant.EVENTBUS_TAG_HTTP_RESULT);
                    }
                } catch (Exception e) {

                }
            }
        });
    }

    /**
     * 净菜上报
     *
     * @param foodMenuId
     * @param data
     * @param type
     */
    public static void uplaodSuttleFoodMaterial(String foodMenuId, List<SideDish> data, int type) {
        if (data == null || data.isEmpty()) {
            Msg msg = new Msg();
            msg.setMsg("数据为空，请查正后再上传");
            msg.setMessage("数据为空，请查正后再上传");
            resultCallback(msg, Constant.EVENTBUS_TAG_HTTP_RESULT);
            return;
        }
        ArrayList<Map<String, Object>> list = new ArrayList();
        for (SideDish foodMaterial : data) {
            Map<String, Object> temp = new HashMap<>();
            temp.put("deviceId", APPDidUtil.getAppDid());
            temp.put("foodMenuId", foodMenuId);
            temp.put("scaleNo", foodMaterial.getNum());
            temp.put("weight", foodMaterial.getWeight());
            temp.put("restWeight", 0);
            temp.put("productId", foodMaterial.getFoodid());
            if (foodMaterial.getWeight() > 0) {
                list.add(temp);
            }
        }
        if (list.isEmpty()) {
            Msg msg = new Msg();
            msg.setMsg("食材重量为空，请查正后再上传");
            msg.setMessage("食材重量为空，请查正后再上传");
            resultCallback(msg, Constant.EVENTBUS_TAG_HTTP_RESULT);
            return;
        }
        HashMap<String, Object> bp = new HashMap<>();
        bp.put("poundList", list);
        bp.put("type", type);
        Log.e(TAG, "paramer=" + JsonHelper.toJson(bp));
        OkHttpManager.HttpPostJson(HttpApi.URL_RECORDPOUND, bp, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                Log.e(TAG, HttpApi.URL_RECORDPOUND);
                Log.e(TAG, e.getMessage());
                Msg msg = new Msg();
                msg.setMsg("设备网络异常，请连接网络");
                msg.setMessage("设备网络异常，请连接网络");
                resultCallback(msg, Constant.EVENTBUS_TAG_HTTP_RESULT);
            }

            @Override
            public void onResponse(String s, int i) {
                try {
                    Msg msg = JsonHelper.parserJson(s, Msg.class);
                    if (msg != null) {
                        resultCallback(msg, Constant.EVENTBUS_TAG_HTTP_RESULT);
                    }
                } catch (Exception e) {

                }
            }
        });
    }




    public static void sendSocketInfo(Map<String, Object> data, String deviceId) {
        sendSocketInfo(data, deviceId, null);
    }

    public static void sendSocketInfo(Map<String, Object> data, String deviceId, final ShowTispMsgDialog dialog) {
        String url = "http://gravity.sayimo.cn:8081/api/ShouhuojiCtl/operate";
        HashMap<String, String> params = new HashMap();
        params.put("macno", deviceId);
        params.put("data", JsonHelper.toJson(data));
//        Log.e(TAG, "推送参数:" + JsonHelper.toJson(params));
        Log.e(TAG, "推送参数:" + JsonHelper.toJson(params));
        OkHttpManager.HttpPost(url, params, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                Log.e(TAG, "Exception=" + e.getMessage());
            }

            @Override
            public void onResponse(String info, int i) {
                Log.e(TAG, "checkDeviceConn=" + info);
                HashMap<String, Object> map = JsonHelper.parserJson(info, new TypeReference<HashMap<String, Object>>() {
                });
                if (map != null && dialog != null) {
                    if (map.containsKey("msg")) {
                        if (map.containsKey("code") && ((int) map.get("code") == 1)) {
                            dialog.setDialog("发送成功", 2000);
                        } else {
                            dialog.setDialog("发送失败，请确认目标机器是否联网", 2000);
                        }
                    }
                }
            }
        });
    }

    public static void getDevices(int type) {
        HashMap<String, Object> params = new HashMap();
        params.put("deviceId", APPDidUtil.getAppDid());
        params.put("type", type);
        Log.e(TAG, "推送参数:" + JsonHelper.toJson(params));
        OkHttpManager.HttpPostJson(HttpApi.GETDEVICES, params, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                Log.e(TAG, "getDevices getDevices=" + e.getMessage());
            }

            @Override
            public void onResponse(String info, int i) {
                try {
                    Log.e(TAG, "getDevices onResponse=" + info);
                    QueryMsgInfo queryMsgInfo = JsonHelper.parserJson(info, new TypeReference<QueryMsgInfo<DeviceInfo>>() {
                    });
                    if (queryMsgInfo != null) {
                        if (queryMsgInfo.getData() != null && !queryMsgInfo.getData().isEmpty()) {
                            EventBus.getDefault().post(queryMsgInfo.getData(), SuttleWeightActivity.EVENT_BUS_TAG);
                        }
                    }
                } catch (Exception e) {

                }
            }
        });
    }

    public static void resultCallback(Msg msg, String tag) {
        EventBus.getDefault().post(msg, tag);
    }


}
